package com.csii.adhoc.util.serializer;

import java.io.*;

/**
 * @Description: jdk序列化工具类
 * @Author: panChuanJiang
 * @Date: 2021-07-19
 */
public class JdkSerializerUtils {

  /**
   * 序列化工具类
   * @param object 序列话对象
   * @return 序列化后的结果
   * @throws IOException 异常
   */
  public static byte[] serialize(Object object) throws IOException{
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
         ObjectOutputStream oos = new ObjectOutputStream(bos)){
      oos.writeObject(object);
      oos.flush();
      return bos.toByteArray();
    }
  }

  /**
   * 反序列化
   * @param bytes 二进制数组
   * @return 反序列话对象
   * @throws IOException 异常
   */
  public static Object deserialize(byte[] bytes) throws IOException{
    try (ByteArrayInputStream bis =  new ByteArrayInputStream(bytes);
         ObjectInputStream ois = new ObjectInputStream(bis)){
      return ois.readObject();
    }catch (ClassNotFoundException e){
      throw new IOException(e.getMessage(),e);
    }
  }
}
